package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func AddFavorite(c *gin.Context) {
	log.Println("AddFavorite called")

	db := getDBConnection()
	defer db.Close()

	var student Student
	if err := c.ShouldBindJSON(&student); err != nil {
		log.Println("Invalid student data:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid student data"})
		return
	}

	_, err := db.Exec("INSERT INTO favorite (id, name, chinese, math, english) VALUES (?, ?, ?, ?, ?)",
		student.Id, student.Name, student.Chinese, student.Math, student.English)
	if err != nil {
		log.Println("Error adding favorite:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Favorite added successfully"})
}
func ListFavorites(c *gin.Context) {
	log.Println("ListFavorites called")

	db := getDBConnection()
	defer db.Close()

	rows, err := db.Query(`
        SELECT id, name, chinese, math, english
        FROM favorite`)
	if err != nil {
		log.Println("Error listing favorites:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}
	defer rows.Close()

	var students []Student
	for rows.Next() {
		var student Student
		if err := rows.Scan(&student.Id, &student.Name, &student.Chinese, &student.Math, &student.English); err != nil {
			log.Println("Error scanning student:", err)
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
			return
		}
		students = append(students, student)
	}

	if err := rows.Err(); err != nil {
		log.Println("Error with rows:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}

	c.HTML(http.StatusOK, "favorite.html", gin.H{
		"favorites": students,
		"title":     "我的收藏",
	})
}
func DeleteFavorite(c *gin.Context) {
	log.Println("DeleteFavorite called")

	db := getDBConnection()
	defer db.Close()

	var favorite Student
	if err := c.ShouldBindJSON(&favorite); err != nil {
		log.Println("Invalid favorite data:", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid favorite data"})
		return
	}

	_, err := db.Exec("DELETE FROM favorite WHERE id = ?", favorite.Id)
	if err != nil {
		log.Println("Error deleting favorite:", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Favorite deleted successfully"})
}
